<template>
  <n-space class="pro-table" vertical>
    <div class="pro-table__header">
      <n-space>
        <n-button type="default" @click="getTableList">刷新</n-button>
      </n-space>
    </div>
    <div class="pro-table__body">
      <n-data-table
        v-bind="$attrs"
        :columns="columns"
        :data="state.tableData"
        :loading="state.loading"
        :single-line="false"
        :scroll-x="1500"
        :pagination="{}"
      />
    </div>
  </n-space>
</template>

<script lang="ts" setup>
defineOptions({ name: 'ProTable' })

import { type DataTableColumns } from 'naive-ui'

export interface ProTableProps {
  /** 列配置项 */
  columns: DataTableColumns
  /** 请求表格数据的 方法 */
  requestApi: (
    params: any,
  ) => Promise<{ list: any[]; pagination: { page: number; size: number; total: number } }>
  /** 是否立即执行一次 requestApi 默认为 true */
  requestAuto?: boolean
}

// 声明 props
const props = withDefaults(defineProps<ProTableProps>(), {
  requestAuto: true,
})

const state = reactive({
  /** 表格数据 */
  tableData: [] as any[],
  /** 表格数据是否请求中 */
  loading: false,
})

/** 获取表格数据 */
async function getTableList(params?: object) {
  try {
    state.loading = true
    // 组装参数
    const totalParams = Object.assign({}, params)
    // 请求接口
    const { list, pagination } = await props.requestApi(totalParams)
    state.tableData = list
  } catch (error) {
    throw `getTableList Error ${error}`
  } finally {
    state.loading = false
  }
}

onMounted(() => {
  props.requestAuto && getTableList()
})

// 对外的暴露
defineExpose({
  getTableList,
})
</script>

<style lang="scss" scoped></style>
